<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-button type="primary" :icon="Plus" @click="addTrademark">
                添加
            </el-button>
        </template>
        <!-- card body -->
        <el-table :style="{ marginBottom: '30px' }" :data="tableData" border stripe>
            <!-- 
                type="index"数据放在对应行的组件上,会根据顺序展示数据索引
                            如果放在列组件上,且该列为selection选择框,则展示的是下拉框的数据
             -->
            <el-table-column label="序号" width="80" align="center" type="index" />
            <!-- 
                prop是对应内容的字段名,不做其他处理会直接展示在视图中
                使用Table-column 插槽 书写展示图片的相应的结构
            -->
            <el-table-column prop="tmName" label="品牌名称" align="center" />
            <el-table-column prop="logoUrl" label="品牌Logo" align="center">
                <!-- 
                    Table-column 插槽
                     -自定义列的内容 作用域参数为 { row, column, $index }
                     -row是当前所在行的所有数据
                 -->
                <template #default="{ row }">
                    <!-- 
                        lazy: 图片懒加载
                     -->
                    <el-image :src="row.logoUrl" :lazy="true" style="height: 60px"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="warning" :icon="Edit" size="small" @click="updataTrademark(row)">
                        修改
                    </el-button>

                    <el-button type="danger" :icon="Delete" size="small" @click="deleteTrademark(row.id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:page-size="limit" v-model:current-page="page" :page-sizes="[3, 5, 10, 15, 20]"
            :pager-count="5" layout="prev, pager, next, sizes" :total="total" />
    </el-card>
    <!-- 
            点击添加和修改,显示弹框
            dialogVisible控制的是对话框的显示与隐藏
        -->
    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id ? '修改品牌' : '添加品牌'">
        <!-- 
        校验时,el-form表单上必带属性
        :model 表单数据
        :rules 校验规则
        校验时,el-form-item必带属性
        prop 需校验字段

        prop放到rules中校验
     -->
        <el-form label-width="100px" :model="newTrademark" :rules="trademarkRule" ref="ruleFormRef">
            <el-form-item label="品牌名称" prop="tmName">
                <!-- v-model受控表单 -->
                <el-input autocomplete="off" v-model="newTrademark.tmName" />
            </el-form-item>
            <el-form-item label="品牌LOGO" prop="logoUrl">
                <!-- 
                    action属性内部封装了请求图片的函数,
                    但是如果函数不走代理,则会产生跨域问题 
                    想要走本地代理可以通过代理前缀实现
                -->
                <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/upload`" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="updateOrAddTrademark">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Trademark",
});
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from "vue"
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
import type { reqTrademarkListRecordsType, reqUpdatetrademarkParamsType } from "@/api/trademarkList"
import { requestTrademarkList, requestUpdatetrademark, requestAddtrademark, requestDeleteTrademark } from "@/api/trademarkList"

//1,table数据逻辑

//初始化响应式table数据
const tableData = ref<reqTrademarkListRecordsType>([])

//2,页码逻辑
//页面数据的类型
interface pageDataType {
    page: number;
    limit: number;
    total: number;
}
//初始化页码数据
const pageData = ref<pageDataType>({
    page: 1,
    limit: 3,
    total: 100
})

//toRefs响应式解构页码属性,toRefs中必须传proxy对象
const { page, limit, total } = toRefs(pageData.value)

//监听页码,页码改变发送请求
watch([page, limit], () => {
    getTrademarkList()
})

//3,获取品牌列表
const getTrademarkList = async () => {
    const result = await requestTrademarkList({
        page: page.value,
        limit: limit.value
    })

    //把请求回来的数据设置给响应数据,替换refs代理对象的数据仍是响应式
    tableData.value = result.records;
    total.value = result.total

};

//初始化页面时请求trademark列表数据
onMounted(() => {
    getTrademarkList()
});

//4,点击添加按钮,弹出对话框逻辑
//控制弹窗的显示隐藏
const dialogFormVisible = ref(false)
//获取当前环境 
const baseUrl = import.meta.env.VITE_API_URL
//初始化更新请求参数
const newTrademark = ref<reqUpdatetrademarkParamsType>({
    logoUrl: "",
    tmName: "",
    id: 0,
})
//品牌LOGO上传逻辑
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    newTrademark.value.logoUrl = response.data
    // console.log("avatar",response);

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

//5,添加逻辑
/* 
点击添加按钮,隐藏对话框并清空清空已添加完成的表单数据
*/
const addTrademark = () => {
    //清空上一次的校验记录
    ruleFormRef.value?.clearValidate()
    console.log("表单验证", ruleFormRef);

    dialogFormVisible.value = true
    //清空修改除回传的数据
    newTrademark.value = {
        logoUrl: "",
        tmName: "",
        id: 0,
    };
}

//6,修改逻辑,回填当前数据
const updataTrademark = (row: reqUpdatetrademarkParamsType) => {
    dialogFormVisible.value = true;
    //拷贝当前行的数据,避免数据共享
    newTrademark.value = { ...row };
}

//7,新增和修改提交
//获取表单实例,判断是否填写了内容,类型是怎么确定的???
const ruleFormRef = ref<FormInstance>()
const updateOrAddTrademark = async () => {
    //全局校验
    try {
        dialogFormVisible.value = false;
        await ruleFormRef.value?.validate()
        try {
            //判断请求类型
            if (newTrademark.value.id) {
                //修改提交
                await requestUpdatetrademark(newTrademark.value)
                ElMessage.success("修改成功")
            } else {
                await requestAddtrademark(newTrademark.value)
                ElMessage.success("新增成功");
                //在第一页新增????
                page.value = 1;
            }
            //重新获取数据
            getTrademarkList();
        } catch (e) {
            ElMessage(newTrademark.value.id ? "修改错误" : "新增错误");
        }
    } catch (e) {
        // ElMessage()
    }


}
//8,删除逻辑
const deleteTrademark = (id: number) => {
    ElMessageBox.confirm(
        '你确定要删除吗?再想想吧',
        '请再次确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            ElMessage({
                type: 'success',
                message: '删除成功',
            });

            //删除trademark请求
            await requestDeleteTrademark(id)
            //重新发送获取数据的请求
            getTrademarkList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '想通啦!不删啦!',
            })
        })
}
//9,表单校验 输入框校验和整体校验
//自定义校验规则
/* 
value: 当前被校验的值
callback是回调函数,回调函数有传参则是错误信息,无传参就是放行
*/
const checkTmNameLength = (rule: any, value: string, callback: any) => {
    if (value.length < 2 || value.length > 5) {
        callback("品牌名的长度必须在2-5个字符之间")
    }
    callback()
}

const trademarkRule = reactive<FormRules>({
    tmName: [
        { required: true, message: '请输入合法的品牌名称', trigger: 'blur' },
        { validator: checkTmNameLength, message: 'L品牌名的长度为2-5个字符', trigger: 'blur' },
    ],
    logoUrl: [
        {
            required: true,
            message: '请上传品牌logo',
            trigger: 'change',
        },
    ]
})

</script>


<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    border: 1px dashed var(--el-border-color);
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
